// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-12-02

package publish

import (
	"context"
	"gitee.com/go-libs/log"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"gitee.com/gomq/sr"
	"github.com/kataras/iris/v12"
	"gomq/app"
	"gomq/app/errs"
	"gomq/app/managers"
)

type Logic struct {
	request  *Request
	response *Response
	sm       managers.ServerManager
}

func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	var (
		has bool
		mgr = managers.Singleton()
	)

	// Validate
	// request body.
	if err = validator.Json(i, o.request); err != nil {
		return
	}

	// Check
	// topic and tag pair.
	if !mgr.MemoryManager().HasRegistry(o.request.Topic, o.request.Tag) {
		err = errs.ErrRegistryNotFound
		return
	}

	// Check
	// server manager.
	if o.sm, has = mgr.ServerManager(); !has {
		err = errs.ErrClusterNotFound
		return
	}

	// Generate response.
	o.response.Tag = o.request.Tag
	o.response.Topic = o.request.Topic
	return
}

func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var err error
	if o.response.Hash, err = o.publish(ctx); err != nil {
		result.New().WithError(err)
	}
	return result.New().With(o.response)
}

func (o *Logic) publish(ctx context.Context) (sr.Hash, error) {
	log.Infofc(ctx, `publish begin`)

	msg := sr.NewPayload(ctx)
	msg.Body = []byte(o.request.MessageBody)
	msg.Keyword = o.request.Keyword
	msg.Tag = o.request.Tag
	msg.Topic = o.request.Topic
	msg.DelaySeconds = app.AnyInt(o.request.DelaySeconds, 0)

	err := o.sm.Publish(msg)
	return msg.Hash, err
}
